//
//  DWDPicSelectViewController.swift
//  照片设置
//
//  Created by Dengdwd on 15/10/19.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit

private let DWD_PIC_CELL = "DWD_PIC_CELL"
private let MAX_COUNT:Int = 9
class DWDPicSelectViewController: UICollectionViewController,DWDPicCellDelegate {
    private var currentIndex:Int = 0
    lazy var pics = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        collectionView!.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(DWDPicCell.self, forCellWithReuseIdentifier: DWD_PIC_CELL)

    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return self.pics.count + (self.pics.count == MAX_COUNT ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DWD_PIC_CELL, forIndexPath: indexPath) as! DWDPicCell
        cell.image = indexPath.item < pics.count ? self.pics[indexPath.item] : nil
        cell.pictureDelegate = self
        return cell
    }
    func didClickRemoveBtn(cell:DWDPicCell) {
        
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pics.count {
            

            pics.removeAtIndex(indexPath.item)

                 collectionView?.reloadData()

           
        }
    }
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        currentIndex = indexPath.item
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问相册")
        return
        }
        let vc = UIImagePickerController()
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
        
    }
}
extension DWDPicSelectViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.imageWithScaleWidth(300)
        
        if currentIndex < pics.count {
        pics[currentIndex] = scaleImage
        }else{
            pics.append(scaleImage)
        }
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}


protocol DWDPicCellDelegate:NSObjectProtocol {

    func didClickRemoveBtn(cell:DWDPicCell)
}

class DWDPicCell: UICollectionViewCell {
    
    weak var pictureDelegate:DWDPicCellDelegate?
    private var image:UIImage? {
        didSet{
            if image != nil {
        picBtn.setImage(image, forState: UIControlState.Normal)
            }else{
            picBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        }
            
            removeBtn.hidden = (image == nil)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    @objc private func didClickReBtn() {
        pictureDelegate?.didClickRemoveBtn(self)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        addSubview(picBtn)
        addSubview(removeBtn)
        picBtn.frame = bounds
        removeBtn.frame.origin = CGPoint(x: 80 - removeBtn.bounds.size.width, y: 0)
        removeBtn.addTarget(self, action: "didClickReBtn", forControlEvents: .TouchUpInside)
        picBtn.userInteractionEnabled = false
        picBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        picBtn.imageView?.clipsToBounds = true
    }
    
    private var picBtn:UIButton = UIButton(imageName: "compose_pic_add")
    private var removeBtn:UIButton = UIButton(imageName: "compose_photo_close")

    

}



